from flask import Flask, jsonify, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from config import config
import os

# 初始化扩展
db = SQLAlchemy()
jwt = JWTManager()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    CORS(app)
    
    # 注册蓝图
    from .routes.auth import auth_bp
    from .routes.user import user_bp
    from .routes.car import car_bp
    from .routes.sales import sales_bp
    from .routes.upload import upload_bp
    from .routes.ai import ai_bp
    
    # 添加基础路由
    @app.route('/')
    def index():
        return jsonify({
            'message': '汽车销售平台API服务已启动',
            'version': '1.0.0',
            'api_docs': '/api/docs'
        })
    
    # 静态文件路由 - 提供头像访问
    @app.route('/uploads/avatar/<path:filename>')
    def avatar_file(filename):
        avatar_dir = os.path.join(app.root_path, '..', 'uploads', 'avatar')
        return send_from_directory(avatar_dir, filename)
    
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(user_bp, url_prefix='/api/user')
    app.register_blueprint(car_bp, url_prefix='/api/car')
    app.register_blueprint(sales_bp, url_prefix='/api/sales')
    app.register_blueprint(upload_bp, url_prefix='/api/upload')
    app.register_blueprint(ai_bp, url_prefix='/api/ai')
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app